let AV = require('leanengine');
let Collect = AV.Object.extend('Collect');
/**
 *
 * @param userId number
 */
function getCollect(userId) {
    let query = new AV.Query('Collect');
    query.equalTo('userId',userId);
    return new Promise((resolve,reject)=>{
        query.find().then(results=>{
            resolve(results)
        },error=>{
            reject(error)
        })
    })
}
function collect(obj,bool) {
    return new Promise((resolve,reject)=>{
        if(bool=='true'){
            let collect = new Collect();
            collect.set('userId',obj.userId);
            collect.set('novel',{name:obj.name,url:obj.url})
            collect.set('read',{name:'',url:''})
            collect.save().then(content=>{
                resolve(true)
            },err =>{
                reject(error)
            });
        }else {
            let query = new AV.Query('Collect');
            query.equalTo('userId',obj.userId);
            query.equalTo("novel.name",obj.name);
            query.find().then(results =>{
                if(results.length){
                    AV.Query.doCloudQuery(`delete from Collect where objectId="${results[0].id}"`).then(function () {
                        // 删除成功
                        resolve(true)
                    }, function (error) {
                        // 异常处理
                        reject(error)
                    });
                }else {
                    resolve(true)
                }
            },error =>{
                reject(error)
            })
        }
    })
}
function read(obj) {
    let collect  = AV.Object.createWithoutData('Collect', obj.id);
    collect.set('read',{name:obj.name,url:obj.url})
    return collect.save();
}
module.exports ={
    collect,
    read,
    getCollect
}